<template>
  <el-dialog title="批量引入" :visible.sync="show" :close-on-click-modal="false" :show-close="!btnLoading" width="1000px" @closed="closed">
    <el-row :gutter="20">
      <el-col :span="8">
        <div class="subtitle">楼栋信息</div>
        <el-table ref="buildingTable" v-loading="buildingLoading" :data="buildingList" size="small" height="530px" @row-click="rowClickBuilding" @selection-change="onSelectBuilding">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="楼栋名称" prop="name" show-overflow-tooltip />
        </el-table>
      </el-col>
      <el-col :span="16">
        <div class="subtitle">工序信息</div>
        <el-scrollbar style="height: 530px; font-size: 12px" v-loading="checkTypeLoading">
          <el-tree ref="tree" :data="checkTypeTree" node-key="mockId" highlight-current default-expand-all show-checkbox>
            <div slot-scope="{ node, data }">
              <div v-if="data.tableId">
                <!-- <el-tag size="mini" type="info" style="margin-right: 10px" v-if="data.specialTypeId">{{ data.specialTypeId | selectEnumLabel(specialTypes) }}</el-tag> -->
                {{ data.tableCode }} - {{ data.tableName }}
                <span v-if="data.specialTypeId"> - {{ data.specialTypeId | selectEnumLabel(specialTypes) }}</span>
              </div>
              <div v-else>
                <el-tag size="mini" style="margin-right: 10px">阶段</el-tag>
                {{ data.typeCode }} - {{ data.typeName }}
                <span v-if="data.specialTypeId"> - {{ data.specialTypeId | selectEnumLabel(specialTypes) }}</span>
              </div>
            </div>
          </el-tree>
        </el-scrollbar>
      </el-col>
    </el-row>

    <div slot="footer">
      <el-button type="primary" :loading="btnLoading" @click="btnSubmit">确 定</el-button>
      <el-button :disabled="btnLoading" @click="show = false">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
// 多个楼栋批量添加工序
import { debounce, flatList2tree, removeEmptyBranch } from '@/utils'
import { getSpecialTypes } from '@/utils/dict/custom'
import { buildingList } from '@/api/common'
import { listCheckType, listCheckTable, addCheckConfigBatchByBuildIds } from '@/api/qualityManage/cq'
export default {
  name: 'BatchAddCheckConfig',
  props: { value: { type: Boolean, default: false } },
  data() {
    return {
      btnLoading: false,
      building: {},
      buildingList: [], // 楼栋
      buildingLoading: false,
      selectedBuilding: [],
      checkTypeList: [], // 阶段
      checkTypeLoading: false,
      checkTypeTree: [], // 阶段树，包含工序
      specialTypes: [] // 专业类别
    }
  },
  computed: {
    show: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  created() {
    this.btnSubmit = debounce(this.onSubmit, 1e3, true)
    getSpecialTypes().then(res => (this.specialTypes = res))
  },
  methods: {
    closed() {
      this.building = {}
      this.buildingList = []
      this.selectedBuilding = []
      this.$refs.tree.setCheckedKeys([])
    },
    open(building = {}) {
      if (!building.id) return this.$message.warning('请选择楼栋')
      this.show = true
      this.building = building
      this.getBuildingList()
      this.getCheckTypeTree()
    },
    // 获取楼栋
    async getBuildingList() {
      const projectId = this.building.project?.id || ''

      this.buildingLoading = true
      const res = await buildingList({ projectId }).catch(() => false)
      this.buildingLoading = false
      if (res === false) return

      this.buildingList = res.data
    },
    // 获取阶段和工序，并组成树
    async getCheckTypeTree() {
      // if (this.checkTypeTree.length) return
      this.checkTypeLoading = true
      const res = await Promise.all([listCheckType(), listCheckTable()]).catch(() => false)
      this.checkTypeLoading = false
      if (res === false) return

      let data1 = res[0].data
      let data2 = res[1].data

      data2.map(i => {
        // 为 node-key 而设
        i.mockId = i.tableId
      })
      data2 = flatList2tree(data2, { id: 'tableId' })
      data2 = removeEmptyBranch(data2)
      data1.map(i => {
        i.mockId = i.typeId
        i.children = data2.filter(t => t.typeId === i.typeId)
      })
      data1 = data1.filter(i => i.children?.length)

      this.checkTypeTree = data1
    },
    rowClickBuilding(row) {
      this.$refs.buildingTable.toggleRowSelection(row)
    },
    onSelectBuilding(val) {
      this.selectedBuilding = val
    },
    async onSubmit() {
      const select1 = this.selectedBuilding
      const select2 = this.$refs.tree.getCheckedNodes()
      if (!select1.length) return this.$message.warning('请选择楼栋')
      if (!select2.length) return this.$message.warning('请选择工序')

      const buildIds = select1.map(i => ({
        projectId: i.parentId,
        buildingId: i.id
      }))

      const checkConfigs = select2
        .filter(i => i.isLeaf)
        .map(i => {
          const { tableId, ...temp } = i
          // tableId 改为 checktableId
          return { ...temp, checktableId: tableId }
        })
      if (!checkConfigs.length) return this.$message.info('选中的工序已全部配置过')

      const opts = { buildIds, checkConfigs }

      this.btnLoading = true
      const res = await addCheckConfigBatchByBuildIds(opts).catch(() => false)
      this.btnLoading = false
      if (res === false) return

      this.msgSuccess('操作成功')
      this.show = false
      this.$emit('ok')
      this.$refs.buildingTable.clearSelection()
      this.$refs.tree.setCheckedKeys([])
    }
  }
}
</script>
<style lang="scss" scoped>
.subtitle {
  font-size: 14px;
  color: #606266;
  padding: 10px;
  border-bottom: 1px solid #dcdfe6;
}
</style>
